package com.pay.ioopos.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.pay.ioopos.KeyInfo;
import com.pay.ioopos.KeyInfoListener;
import com.pay.ioopos.PwdValidator;
import com.pay.ioopos.R;
import com.pay.ioopos.StatusListener;
import com.pay.ioopos.fragment.PwdInputFragment.OnPwdListener;


public abstract class AbstractPwdSetFragment extends AbstractFragment implements KeyInfoListener, OnPwdListener {
    private PwdInputFragment pwdInput = new PwdInputFragment();
    private StatusListener listener;
    private boolean isValidOldPwd = false;
    private TextView labelView;
    private String newPwd;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_password, container, false);

        pwdInput.setOnPwdListener(this);

        labelView = view.findViewById(R.id.pwd_input_label);
        labelView.setText(R.string.pwd_type_in_old);

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.password_main_container, pwdInput);
        fragmentTransaction.commit();

        return view;
    }

    @Override
    public boolean onKeyDown(KeyInfo keyInfo) {
        return pwdInput.onKeyDown(keyInfo);
    }

    @Override
    public void finish(String pwd) {
        if (!isValidOldPwd) {
            if (validator().isValid(pwd)) {
                isValidOldPwd = true;
                labelView.setText(R.string.pwd_type_in_new);
            } else {
                showToast(getString(R.string.pwd_old_incorrect));
                labelView.setText(R.string.pwd_type_in_old);
            }
            clearInput();
            return;
        }
        if (null == newPwd) {
            newPwd = pwd;
            labelView.setText(R.string.pwd_type_in_twice);
            clearInput();
            return;
        }
        if (!pwd.equals(newPwd)) {
            showToast(getString(R.string.pwd_twice_incorrect));
            newPwd = null;
            labelView.setText(R.string.pwd_type_in_new);
            clearInput();
            return;
        }
        onSet(pwd);
        if (null != listener) {
            listener.onSuccess("密码修改成功");
        }
    }

    public void setListener(StatusListener listener) {
        this.listener = listener;
    }

    protected abstract PwdValidator validator();

    protected abstract void onSet(String pwd);

    private void clearInput() {
        handleDelay(pwdInput::clear, 300);
    }

}
